package ezookeeper

import (
	"encoding/json"
	"git.edaijia-inc.cn/edaijia/ego/elogger"
	"github.com/samuel/go-zookeeper/zk"
	"strings"
	"time"
)

type Config struct {
	Hosts string `ini:"hosts"`
	Path  string `ini:"path"`
}

type EZookeeper struct {
	Config *Config
	client *zk.Conn
}

func InitEZookeeper(conf *Config) *EZookeeper {
	hosts := strings.Split(conf.Hosts, ",")
	client, _, err := zk.Connect(hosts, time.Second*5)
	if err != nil {
		elogger.Error("ezookeeper connect error: ", err)
	}
	return &EZookeeper{conf, client}
}

func (e *EZookeeper) Create(zone, key string, data []byte) error {
	defer e.client.Close()
	// 开始监听path
	_, _, event, err := e.client.ExistsW(e.Config.Path)
	if err != nil {
		elogger.Error("ezookeeper ExistsW error: ", err.Error())
	}
	go e.watchZkEvent(event)
	keyPath := e.CreateKey(e.Config.Path, zone, key)
	_, err = e.client.Create(keyPath, data, 0, zk.WorldACL(zk.PermAll))
	if err != nil {
		elogger.Error("ezookeeper Create error: ", err.Error())
	}
	return err
}

func (e *EZookeeper) watchZkEvent(ev <-chan zk.Event) {
	<-ev
}

func (e *EZookeeper) Update(zone, key string, data []byte) error {
	keyPath := e.CreateKey(e.Config.Path, zone, key)
	defer e.client.Close()
	// 开始监听path
	_, _, event, err := e.client.ExistsW(e.Config.Path)
	if err != nil {
		elogger.Error("ezookeeper ExistsW error: ", err.Error())
	}
	_, sate, err := e.client.Get(keyPath)
	if err != nil {
		elogger.Error("ezookeeper,Update,get error: ", err.Error())
		return err
	}
	go e.watchZkEvent(event)
	_, err = e.client.Set(keyPath, data, sate.Version)
	if err != nil {
		elogger.Error("ezookeeper Update error: ", err.Error())
	}
	return err
}

func (e *EZookeeper) GetJsonConfig(zone, key string, value interface{}) error {
	keyPath := e.CreateKey(e.Config.Path, zone, key)
	defer e.client.Close()
	data, _, err := e.client.Get(keyPath)
	if err != nil {
		elogger.Error("ezookeeper,Get,get error: ", err.Error())
	}
	if len(data) == 0 {
		return nil
	}
	err = json.Unmarshal(data, value)
	if err != nil {
		elogger.Error("ezookeeper,Get,json Unmarshal error: ", err.Error())
	}
	return err
}

func (e *EZookeeper) CreateKey(path, zone, key string) string {
	return path + "/" + zone + "/" + key
}
